package model

import (
	"errors"
	"fmt"
	"github.com/jmoiron/sqlx"
	"time"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
)

// 收货地址相关
type ShopUserAddressModel struct {
	ID         int64  `db:"id" json:"id" form:"id" binding:"required"`
	UID        int64  `db:"uid" json:"uid" form:"uid" binding:"required"`
	Area       string `db:"area" json:"area" form:"area"`
	Name       string `db:"name" json:"name" form:"name"`
	Phone      string `db:"phone" json:"phone" form:"phone"`
	PostCode   string `db:"post_code" json:"post_code" form:"post_code"`
	Address    string `db:"address" json:"address" form:"address"`
	Status     int    `db:"status" json:"status" form:"status"`
	CreateTime int64  `db:"create_time" json:"create_time" form:"create_time"`
	UpdateTime int64  `db:"update_time" json:"update_time,omitempty" form:"update_time"`
}

// 获取用户收货地址信息
// Auth: hzp
func ListShopUserAddress(Uid int64) (res []ShopUserAddressModel, err error) {

	err = sqlx.Select(config.C.DB.DB, &res, "SELECT id,uid,area,name,phone,post_code,address,status,create_time,update_time "+
		" FROM shop_user_addr WHERE uid = ? AND `status` <> 2", Uid)
	if err != nil {
		return res, err
	}

	return
}

// 删除收货地址
// Auth: hzp
func DelShopUserAddress(Uid, Id int64) (err error) {

	res := sqlx.MustExec(config.C.DB.DB, "UPDATE shop_user_addr SET `status` = 2 WHERE uid = ? AND id = ?", Uid, Id)
	_, err = res.RowsAffected()
	if err != nil {
		return err
	}
	return
}

// 修改收货地址
// Auth: hzp
func UpdateShopUserAddress(params ShopUserAddressModel) (err error) {

	res := sqlx.MustExec(config.C.DB.DB, "UPDATE shop_user_addr SET `status`=?,`name`=?,`area`=?,phone=?,post_code,"+
		" update_time=unix_timestamp(now()) WHERE uid = ? AND id = ?", params.Status, params.Name, params.Area,
		params.Phone, params.PostCode, params.UID, params.ID)
	_, err = res.RowsAffected()
	if err != nil {
		return err
	}
	return
}

// 新增收货地址
// Auth: hzp
func CreateShopUserAddress(params ShopUserAddressModel) (err error) {

	res := sqlx.MustExec(config.C.DB.DB, "INSERT INTO shop_user_addr (uid, name, area, phone, address, post_code, "+
		" create_time) VALUES (?, ?, ?, ?, ?, ?, unix_timestamp(now())) ", params.UID, params.Name, params.Area,
		params.Phone, params.Address, params.PostCode)
	_, err = res.LastInsertId()
	if err != nil {
		return err
	}
	return
}

// 商品评价相关
type ShopGoodsCommentModel struct {
	ID         int64  `db:"id" json:"id" form:"id" binding:"required"`
	UID        int64  `db:"uid" json:"uid" form:"uid" binding:"required"`
	GId        int64  `db:"gid" json:"gid" form:"gid" binding:"required"`
	Phone      string `db:"phone" json:"phone" form:"phone"`
	Content    string `db:"content" json:"content" form:"content"`
	CreateTime int64  `db:"create_time" json:"create_time" form:"create_time"`
}

// 查询商品评价列表
// Auth: hzp
func ListShopGoodsComment(Gid int64, page, pageSize int) (res []ShopGoodsCommentModel, err error) {

	start := (page - 1) * pageSize
	err = sqlx.Select(config.C.DB.DB, &res, "SELECT id,uid,gid,phone,content,create_time FROM shop_goods_comment "+
		"WHERE gid=? AND `status`=1 order by create_time DESC LIMIT ?, ?", Gid, start, pageSize)
	if err != nil {
		return res, err
	}
	return
}

// 删除商品评论
// Auth: hzp
func DelShopGoodsComment(Id int64) (err error) {

	res := sqlx.MustExec(config.C.DB.DB, "UPDATE shop_goods_comment SET status = 0 WHERE id = ?", Id)
	_, err = res.RowsAffected()
	if err != nil {
		return err
	}
	return
}

// 发布商品评论
// Auth: hzp
func CreateShopGoodsComment(params ShopGoodsCommentModel) (err error) {

	res := sqlx.MustExec(config.C.DB.DB, "INSERT INTO shop_goods_comment (gid,uid,phone,content,create_time,status) "+
		" VALUES (?, ?, ?, ?, unix_timestamp(now()), 1)", params.GId, params.UID, params.Phone, params.Content)
	_, err = res.LastInsertId()
	if err != nil {
		return err
	}
	return
}

// 商品信息相关
type ShopGoods struct {
	GId           int64   `db:"gid" json:"gid"`
	Name          string  `db:"name" json:"name"`
	Desc          string  `db:"desc" json:"desc"`
	Poster        string  `db:"poster" json:"poster"`
	Stock         int     `db:"stock" json:"stock"`
	OriginPrice   float64 `db:"origin_price" json:"origin_price"`
	CvntPrice     float64 `db:"cvnt_price" json:"cvnt_price"`
	CvntPriceText string  `db:"cvnt_price_text" json:"cvnt_price_text"`
	EthPrice      float64 `db:"eth_price" json:"eth_price"`
	EthPriceText  string  `db:"eth_price_text" json:"eth_price_text"`
	BtcPrice      float64 `db:"btc_price" json:"btc_price"`
	BtcPriceText  string  `db:"btc_price_text" json:"btc_price_text"`
	TotalStock    int     `db:"total_stock" json:"total_stock"`
	Sale          int     `db:"sale" json:"sale"`
	SaleStart     int     `db:"sale_start" json:"sale_start"`
	Buy           int     `db:"buy" json:"buy"`
	BuyStart      int     `db:"buy_start" json:"buy_start"`
	Status        int     `db:"status" json:"status"`
	CreateTime    string  `db:"create_time" json:"create_time"`
}

// 获取商品详情信息
func GetShopGoodsInfo(Gid int64) (res ShopGoods, err error) {

	err = sqlx.Get(config.C.DB.DB, &res, "SELECT gid,`desc`,`title` as `name`,origin_price,poster,stock,total_stock,buy,buy_start FROM"+
		" shop_goods WHERE gid=? AND `status`=20 ORDER BY create_time desc", Gid)
	if err != nil {
		return res, err
	}
	return
}

// 获取商品列表接口
func ListShopGoods(page, pageSize int) (res []ShopGoods, err error) {

	start := (page - 1) * pageSize
	err = sqlx.Select(config.C.DB.DB, &res, "SELECT gid,`desc`,`title` as `name`,origin_price,poster,stock,total_stock,buy,buy_start FROM"+
		" shop_goods WHERE `status`=20 ORDER BY create_time desc LIMIT ?,?", start, pageSize)
	if err != nil {
		return res, err
	}
	return
}

// 获取所有商品
func GetShopList(page, per int) (res []ShopGoods, err error) {
	start := (page - 1) * per
	err = sqlx.Select(config.C.DB.DB, &res, "SELECT gid, IFNULL(`desc`, '') AS `desc`, title as `name`, origin_price, cvnt_price, cvnt_price_text, eth_price, eth_price_text,btc_price, btc_price_text, "+
		"poster,stock,total_stock,buy,buy_start, status, FROM_UNIXTIME(create_time, '%Y/%m/%d %H:%i:%s') AS create_time FROM "+
		"shop_goods ORDER BY gid desc LIMIT ?,?", start, per)
	if err != nil {
		e.Log("err", err.Error())
		return res, err
	}
	return
}

type EditShopParams struct {
	GId           int     `form:"gid"`
	Name          string  `form:"name" binding:"required"`
	Poster        string  `form:"poster" binding:"required"`
	OriginPrice   float64 `form:"origin_price"`
	CvntPrice     float64 `form:"cvnt_price"`
	CvntPriceText string  `form:"cvnt_price_text"`
	EthPrice      float64 `form:"eth_price"`
	EthPriceText  string  `form:"eth_price_text"`
	BtcPrice      float64 `form:"btc_price"`
	BtcPriceText  string  `form:"btc_price_text"`
	TotalStock    int     `form:"total_stock" binding:"required"`
	Stock         int     `form:"stock"`
	SaleStart     int     `form:"sale_start"`
	BuyStart      int     `form:"buy_start"`
	Desc          string  `form:"desc"`
}

//新增商品
func AddNewShop(params EditShopParams) (err error) {
	sqlStr := fmt.Sprintf("INSERT INTO shop_goods SET `title` = '%s', poster = '%s', origin_price = %f, cvnt_price = %f, eth_price = %f, btc_price = %f, "+
		"total_stock = %d, stock = %d, sale_start = %d, buy_start = %d, ", params.Name, params.Poster, params.OriginPrice, params.CvntPrice, params.EthPrice, params.BtcPrice,
		params.TotalStock, params.Stock, params.SaleStart, params.BuyStart)
	if len(params.CvntPriceText) > 0 {
		sqlStr += fmt.Sprintf("cvnt_price_text = '%s', ", params.CvntPriceText)
	}
	if len(params.EthPriceText) > 0 {
		sqlStr += fmt.Sprintf("eth_price_text = '%s', ", params.EthPriceText)
	}
	if len(params.BtcPriceText) > 0 {
		sqlStr += fmt.Sprintf("btc_price_text = '%s', ", params.BtcPriceText)
	}
	if len(params.Desc) > 0 {
		sqlStr += fmt.Sprintf("`desc` = '%s', ", params.Desc)
	}
	sqlStr += fmt.Sprintf("create_time = %d", time.Now().Unix())

	res := sqlx.MustExec(config.C.DB.DB, sqlStr)
	_, err = res.LastInsertId()
	if err != nil {
		e.Log("err", err.Error())
		return errno.DbError
	}
	return
}

//修改商品
func EditShop(params EditShopParams) (err error) {
	if params.GId <= 0 {
		return errors.New("gid不能为空")
	}

	sqlStr := fmt.Sprintf("UPDATE shop_goods SET title = '%s', poster = '%s', origin_price = %f, cvnt_price = %f, eth_price = %f, btc_price = %f, "+
		"total_stock = %d, stock = %d, sale_start = %d, buy_start = %d, ", params.Name, params.Poster, params.OriginPrice, params.CvntPrice, params.EthPrice, params.BtcPrice,
		params.TotalStock, params.Stock, params.SaleStart, params.BuyStart)
	if len(params.CvntPriceText) > 0 {
		sqlStr += fmt.Sprintf("cvnt_price_text = '%s', ", params.CvntPriceText)
	}
	if len(params.EthPriceText) > 0 {
		sqlStr += fmt.Sprintf("eth_price_text = '%s', ", params.EthPriceText)
	}
	if len(params.BtcPriceText) > 0 {
		sqlStr += fmt.Sprintf("btc_price_text = '%s', ", params.BtcPriceText)
	}
	if len(params.Desc) > 0 {
		sqlStr += fmt.Sprintf("`desc` = '%s', ", params.Desc)
	}
	sqlStr += fmt.Sprintf("update_time = %d WHERE gid = %d", time.Now().Unix(), params.GId)

	res := sqlx.MustExec(config.C.DB.DB, sqlStr)
	_, err = res.LastInsertId()
	if err != nil {
		e.Log("err", err.Error())
		return errno.DbError
	}
	return
}
